package org.kumas.bigdata.hdfs3.rpc;

import org.apache.hadoop.io.Writable;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.Arrays;

/*************************************************
 * TODO_Kumas
 *  Author： KumasZhang
 *  DateTime： 2021-12-06 9:01
 *  Description： 
 **/
public class Response implements Writable {
    public static final int RESPONSE_OK = 0;
    public static final int RESPONSE_ERROR = 1;

    public int code;
    public String msg;
    public byte[] data;
    private int datalen;

    public Response() {

    }

    public static Response fail(String msg, byte[] data) {
        return new Response(RESPONSE_ERROR, msg, data);
    }

    public static Response fail(String msg) {
        return new Response(RESPONSE_ERROR, msg, null);
    }

    public static Response ok(String msg, byte[] data) {
        return new Response(RESPONSE_OK, msg, data);
    }

    public static Response ok(String msg) {
        return new Response(RESPONSE_OK, msg, null);
    }

    public Response(int code, String msg, byte[] data) {
        this.code = code;
        this.msg = msg;
        this.data = data;
        if (data == null) {
            datalen = 0;
        } else {
            datalen = data.length;
        }
    }

    @Override
    public void write(DataOutput out) throws IOException {
        out.writeInt(code);
        out.writeUTF(msg);
        out.writeInt(datalen);
        if (datalen > 0) {
            out.write(data);
        }
    }

    @Override
    public void readFields(DataInput in) throws IOException {
        code = in.readInt();
        msg = in.readUTF();
        datalen = in.readInt();
        if (datalen > 0) {
            data = new byte[datalen];
            in.readFully(data,0, datalen);
        } else {
            data = null;
        }
    }

    @Override
    public String toString() {
        return "Response{" +
                "code='" + code + '\'' +
                ", msg='" + msg + '\'' +
                ", data=" + Arrays.toString(data) +
                '}';
    }
}
